package com.yanyuan.mybaits.config;

import com.yanyuan.mybaits.config.xml.Command;
import com.yanyuan.mybaits.config.xml.Mapper;
import com.yanyuan.mybaits.config.xml.XmlBuilder;
import com.yanyuan.mybaits.dao.IMessage;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description mapper注册器
 * @Author yanyuan
 * @Date 11:53 2020/3/18
 * @Version 1.0
 **/
public class MapperRegistry {

    private Map<Class<?>, MapperProxyFactory<?>> knowMapper = new HashMap<>();

    public boolean hasMapper(Class<?> type){
        return knowMapper.containsKey(type);
    }

    public <T> T getMapper(Class<T> type, SqlSession sqlSession){
        if(!hasMapper(type)){
            throw new RuntimeException(" type [" + type + "]  not exists ");
        }
        MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knowMapper.get(type);

        return mapperProxyFactory.newInstance(sqlSession);
    }

    public <T> void addMapper(Class<T> type, Map<Method, Command> methodCache){
        if(!type.isInterface()){
            return;
        }
        if(hasMapper(type)){
            throw new RuntimeException(" type [" + type + "] exists knowMapper");
        }

        knowMapper.put(type, new MapperProxyFactory<>(type, methodCache));
    }


}
